/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.client;


import com.gwtext.client.core.EventObject;  
import com.gwtext.client.widgets.*;

import com.gwtext.client.widgets.event.TabPanelListenerAdapter;  
import com.gwtext.client.widgets.layout.VerticalLayout;  
import com.gwtext.client.widgets.menu.BaseItem;  
import com.gwtext.client.widgets.menu.Item;  
import com.gwtext.client.widgets.menu.Menu;  
import com.gwtext.client.widgets.menu.event.BaseItemListenerAdapter;

import com.gwtext.client.widgets.layout.HorizontalLayout;  

import java.util.*;

import nfse.gui.client.data.SnapShotDataTypeCategoryRecord;

public class SnapShotTab extends Panel
{
	     private TabPanel tabPanel;  
	     private Menu menu;  
	     private HashMap snapShotDataMap; 
	     private HashMap sensorTabsMap = new HashMap();
	     private int rotationalViewIndex = 0;
	     
     	 String[] dataTypes =  {"ProofPoint","Firewall","Netflow"}; 
	     
	     private Panel targetPanel = null;
	     
	     	public SnapShotTab(HashMap snapShotDataMap)
	     	{
	     		this.snapShotDataMap = snapShotDataMap;
	     	}
	     
	     	
	     	public void testClass()
	     	{
	     		//This just tests that something can be displayed in the panel
	     		this.setHtml("Hello John");
	     	}
	     	
	     	public void getNewRotationalView()
	     	{
	     		try
	     		{
	     			String title = tabPanel.getActiveTab().getTitle();

	     			if (rotationalViewIndex >= dataTypes.length)
						rotationalViewIndex = 0;
					String dataType = dataTypes[rotationalViewIndex];
					targetPanel = (Panel)addTab(dataType,(HashMap)snapShotDataMap.get(dataType));
					targetPanel.setTitle("Rotational View - " + dataType);
				    tabPanel.activate(0);
					    
					 Component[] items = tabPanel.getItems();  
                     for (int i = 0; i < items.length; i++) 
                     {  
                          Component component = items[i];  
					      if (component.getId().equals(tabPanel.getActiveTab().getId())) 
					      {     		                        	   
					          tabPanel.remove(component);  
					          break;
					       }  
					}  
					tabPanel.insert(0, targetPanel);				
					if (title.indexOf("Rot") != -1)
						tabPanel.activate(0);
					else
					{
						for (int q = 0; q < dataTypes.length; q++)
						{
							if (title.equals(dataTypes[q]))
								tabPanel.activate(q + 1);
						}
					}
					rotationalViewIndex++;
	     		}
	     		catch (Exception ex)
	     		{
	     			System.out.println("Failed in here with " + ex.getMessage());
	     			ex.printStackTrace();
	     		}	     				
	     	}
	     	
	     	public void buildSnapShotTabPanel()
	     	{
	         this.setBorder(false);  
	         //this.setPaddings(15);  
	         Panel verticalPanel = new Panel();  
	         verticalPanel.setLayout(new VerticalLayout(15));  
	   	   
	         tabPanel = new TabPanel();  
	         tabPanel.setResizeTabs(true);  
	         tabPanel.setMinTabWidth(115);  
	         tabPanel.setTabWidth(170);  
	         tabPanel.setAutoWidth(true);
	         tabPanel.setHeight(425);  
	         tabPanel.setActiveTab(0);  
	   
	         tabPanel.addListener(new TabPanelListenerAdapter() {  
	             public void onContextMenu(TabPanel source, Panel tab, EventObject e) {  
	                 showMenu(tab, e);  
	             }  
	         });  
	   
	         
	         //Panel rotationalTab = addTab("Rotational View - " + "Firewall", (HashMap)snapShotDataMap.get("Firewall"));
	         Panel targetPanel = addTab("Rotational View - " + "Firewall", (HashMap)snapShotDataMap.get("Firewall"));
	         tabPanel.add(targetPanel);
	         //tabPanel.add(rotationalTab);	         
	         //sensorTabsMap.put("Rotational View",rotationalTab);
	         sensorTabsMap.put("Rotational View",targetPanel);
	         
	         Iterator ssdmIt = snapShotDataMap.keySet().iterator();
	         while (ssdmIt.hasNext())
	         {
	        	 String dataType = (String)ssdmIt.next();
	        	 HashMap snapShotDataTypeMap = (HashMap)snapShotDataMap.get(dataType);
	        	 Panel tab = addTab(dataType,snapShotDataTypeMap);
        	 	tabPanel.add(tab);
        	 	sensorTabsMap.put(dataType,tab);
	         }
	         verticalPanel.add(tabPanel);  
	         
	         this.add(verticalPanel);  	  
	     }  
	   
	     private void showMenu(final Panel tab, EventObject e) {  
	         if (menu == null) {  
	             menu = new Menu();  
	             Item close = new Item("Close Tab");  
	             close.setId("close-tab-item");  
	             close.addListener(new BaseItemListenerAdapter() {  
	                 public void onClick(BaseItem item, EventObject e) {  
	                     tabPanel.remove(tabPanel.getActiveTab());  
	                 }  
	             });  
	             menu.addItem(close);  
	   
	             Item closeOthers = new Item("Close Other Tabs");  
	             closeOthers.setId("close-others-item");  
	             closeOthers.addListener(new BaseItemListenerAdapter() {  
	                 public void onClick(BaseItem item, EventObject e) {  
	                     Component[] items = tabPanel.getItems();  
	                     for (int i = 0; i < items.length; i++) {  
	                         Component component = items[i];  
	                         if (!component.getId().equals(tabPanel.getActiveTab().getId())) {  
	                             tabPanel.remove(component);  
	                         }  
	                     }  
	                 }  
	             });  
	             menu.addItem(closeOthers);  
	         }  
	   
	         BaseItem closeOthers = menu.getItem("close-others-item");  
	         if (tabPanel.getItems().length == 1) {  
	             closeOthers.disable();  
	         } else {  
	             closeOthers.enable();  
	         }  
	         menu.showAt(e.getXY());  
	     }  
	   
	     public Panel addTab(String dataType, HashMap snapShotDataTypeMap) {  
	
	    	 String[] snapShotHeaders = {"Top Sources","TopTargets","Top Destinations"};
	    	    String[][] snapShotColumnHeaders = 
	    	    {
	    	    		{"Address","Hits"},
	    	    		{"Address","Hits"},
	    	    		{"Port","Hits"},
	    	    };
	    	    
	    	 Panel tab = new Panel();  
	         //tab.setAutoScroll(true);  
	         tab.setTitle(dataType);	        
	         //tab.setWidth(900);
	         tab.setAutoWidth(true);
	         tab.setHeight(400);
	        // tab.setIconCls("tab-icon");  
	          tab.setLayout(new com.gwtext.client.widgets.layout.TableLayout(snapShotHeaders.length));

	         
			for (int j = 0; j < snapShotDataTypeMap.size(); j++)
			{
				 ArrayList categoryRecords  = (ArrayList)snapShotDataTypeMap.get(snapShotHeaders[j]);
				 Iterator catIt = categoryRecords.iterator();
				
				
				 Panel localPanel = new Panel();
			     //localPanel.setLayout(new com.gwtext.client.widgets.layout.TableLayout(1));
			     localPanel.setLayout(new com.gwtext.client.widgets.layout.VerticalLayout());
    			 localPanel.setTitle(snapShotHeaders[j]);
    			 localPanel.setAutoScroll(true);
    			 localPanel.setHeight(400);
    			 localPanel.setPaddings(5);
    			 int firstLine = 0;
				while (catIt.hasNext())
				{									
					SnapShotDataTypeCategoryRecord ssRecord = (SnapShotDataTypeCategoryRecord)catIt.next();
					
					
					//Column Headers (Address Hits or Port Hits
					if (firstLine == 0)
					{
						Panel linePanel = new Panel();
						linePanel.setLayout(new HorizontalLayout(5));
						if (ssRecord.getAddress() != null)
						{
						  HTMLPanel hPanel = new HTMLPanel();
						  hPanel.setWidth(100);
						  hPanel.setHtml("<center>Address</center>");
						  hPanel.setStyle("font-size: 8pt;");
						  linePanel.add(hPanel);
						}
						else
						{
							  HTMLPanel hPanel = new HTMLPanel();
							  hPanel.setWidth(100);
							  hPanel.setHtml("<center>Port</center>");
							  hPanel.setStyle("font-size: 8pt;");
							  linePanel.add(hPanel);
						}
						
					  HTMLPanel hPanel = new HTMLPanel();
					  hPanel.setWidth(100);
					  hPanel.setHtml("<center>Hits</center>");
					  hPanel.setStyle("font-size: 8pt;");
   					  linePanel.add(hPanel);
					  localPanel.add(linePanel);
					  firstLine++;
					}
					
					if (ssRecord.getAddress() != null)
					{						 
						Panel linePanel = new Panel();
						linePanel.setLayout(new HorizontalLayout(5)); 
						String address = createTextHTML(ssRecord.getAddress()) ;
						String hits = createBarGraphHTML(ssRecord.getHits(),2000);
						linePanel.add(new HTMLPanel(address));
						linePanel.add(new HTMLPanel(hits));
						localPanel.add(linePanel);
					}
					else if (ssRecord.getPort() != null)
					{
						Panel linePanel = new Panel();
						linePanel.setLayout(new HorizontalLayout(5)); 
						String port = createTextHTML(ssRecord.getPort());
						String hits = createBarGraphHTML(ssRecord.getHits(),2000);
						linePanel.add(new HTMLPanel(port));
						linePanel.add(new HTMLPanel(hits));
						localPanel.add(linePanel);
					}
					
				} //End while (catIt.hasNext()) Populates the category of a Data Type (Top Sources is a category)

				//localPanel.setAutoWidth(true);
				localPanel.setWidth(332);
	 		tab.add(localPanel);
					
			} //for (int j = 0; j < snapShotDataTypeMap.size(); j++)  Populates the DataType Table . There can be n categories per Data Type Table

			return tab;
	     }  

	 	private String createBarGraphHTML(String rawData, int maxHit)
		{				
			float temp = (new Float(rawData).floatValue())/maxHit;		
			int barGraphPercent = (int)(temp * 100);
			return "<div class='graph'> <strong class='bar' style='width:" +  barGraphPercent +"%;'><span>" +  rawData + "</span></strong></div>";
			
		}
	 	
		
		private String createTextHTML(String rawData)
		{
			return "<div class='non-graph-text' style='text-align:right' ><strong class='bar' > <span>" +  rawData + "</span></strong></div>";
			//return "<div class='non-graph-text' style='text-align:right'> <span>" +  rawData + "</span></div>";
		}


		public HashMap getSensorTabsMap()
		{
			return sensorTabsMap;
		}


		public void setSensorTabsMap(HashMap sensorTabsMap)
		{
			this.sensorTabsMap = sensorTabsMap;
		}


	     
}
